#include "Udp_client.hpp"
#include<cstring>
#include <pthread.h>

using namespace std;

static void usage(string proc)
{
    cout<<"Usage\n\t"<<proc<<" ip "<<" port\n"<<endl;
}

void *rec(void *argc)
{
    int sock = *(static_cast<int *>(argc));

    while (true)
    {
        // 接受
        char buffer[2048];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        int n = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            
            cout << temp.sin_port<<"#" << buffer << endl;
        }
    }
}

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }

    pthread_t t1;
    string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);

    int sock = socket(AF_INET,SOCK_DGRAM,0);
    
    
    if (sock < 0)
    {
        cerr << "creat socket error: " << errno << " :" << strerror(errno) << endl;
        exit(SOCKET_ERR);
    }
    cout << "creat socket success: " << sock << endl;

    //client不需要bind，让os自动给其bind

    pthread_create(&t1,nullptr,rec,&sock);


    //明确server是谁
    struct sockaddr_in server;
     bzero(&server,sizeof(server));
     server.sin_family = AF_INET;
     server.sin_port = htons(server_port);
     server.sin_addr.s_addr = inet_addr(server_ip.c_str());

     while(true)
     {
        string mess;
        //cout<<"ydd的服务器#";

        //cin>>mess;
        getline(cin,mess);
        //cout<<"getline(cin,mess);成功"<<endl;

        //发送
        sendto(sock,mess.c_str(),mess.size(),0,(struct sockaddr *)&server,sizeof(server));

        
     }

    return 0;
}